package com.block.merchant.service.infotype;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.common.service.LogFactory;
import com.block.common.vo.ResponseVo;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.factory.PushApi2Factory;
import com.block.datapush.factory.PushApiFactory;
import com.block.datapush.model.result.PushApiResult;
import com.block.db.entity.*;
import com.block.db.mapper.MerchantDataPushCountInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.merchant.enums.CheckStatusEnum;
import com.block.merchant.enums.FlowRateTypeEnum;
import com.block.merchant.model.dto.CheckSourceTypeDTO;
import com.block.merchant.model.dto.DataPushCountDTO;
import com.block.merchant.model.dto.MerchantOrderDTO;
import com.block.merchant.model.result.DataPushResult;
import com.block.merchant.model.result.MatchMerchantInfo;
import com.block.merchant.service.IMerchantDataPushCountInfoService;
import com.block.merchant.service.IMerchantDataPushInfoService;
import com.block.merchant.service.IMerchantHandleService;
import com.block.sms.dto.SmsParamDTO;
import com.block.sms.service.ISmsRecordService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;

@Service
public class MerchantApiSHandleService implements IMerchantHandleService {

    private static final Logger log = LogFactory.getMerchantLog();
    private static final Logger sourceLog = LogFactory.getSourceLog();

    @Autowired
    IMerchantDataPushInfoService merchantDataPushInfoService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    IMerchantDataPushCountInfoService merchantDataPushCountInfoService;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    ISmsRecordService smsRecordService;
    @Autowired
    RestTemplate restTemplate;

    /**
     * 商户信息匹配
     * @return
     */
    @Override
    public MatchMerchantInfo matchWithMerchant(MerchantBaseInfo merchantBaseInfo, MerchantOrderDTO merchantOrderDTO, MemberSourceInfo memberSourceInfo) throws Exception {

        MatchMerchantInfo matchMerchantInfo =  new MatchMerchantInfo();
        matchMerchantInfo.setMatchSuccess(false);
        matchMerchantInfo.setInfoId(merchantOrderDTO.getInfoId());
        matchMerchantInfo.setInfoType(merchantOrderDTO.getInfoType());
        matchMerchantInfo.setShowPosition(merchantOrderDTO.getShowPostion());

        matchMerchantInfo.setTaskId(merchantOrderDTO.getTaskId());
        matchMerchantInfo.setProfitAmount(merchantOrderDTO.getPriceAmount());
        matchMerchantInfo.setApproveFlag(0);

        /**
         * 生成匹配记录
         */
        MerchantDataPushInfo dataPushInfo = merchantDataPushInfoService.saveInitPushData(memberSourceInfo, merchantOrderDTO);

        String orderNo = String.valueOf(dataPushInfo.getId());
        PushApiKeyParam pushApiKeyParam = merchantDataPushInfoService.getPushKeyInfo(merchantBaseInfo, memberSourceInfo);
        // 设置授权协议地址
        matchMerchantInfo.setProtocolUrl(pushApiKeyParam.getProtocolUrl());
        matchMerchantInfo.setPushId(orderNo);

        JSONObject extJson = new JSONObject();

        DataPushCountDTO dataPushCountDTO = new DataPushCountDTO();
        dataPushCountDTO.setDateInfo(LocalDate.now().toString());
        dataPushCountDTO.setInfoId(merchantBaseInfo.getId());
        dataPushCountDTO.setInfoName(merchantBaseInfo.getInfoName());
        ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(memberSourceInfo.getChannelCode());
        if (baseInfoByCode != null) {
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APP.getValue())) {
                dataPushCountDTO.setCheckNumberApp(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.H5.getValue())) {
                dataPushCountDTO.setCheckNumberH5(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIS.getValue())) {
                dataPushCountDTO.setCheckNumberApis(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIB.getValue())) {
                dataPushCountDTO.setCheckNumberApib(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.WX.getValue())) {
                dataPushCountDTO.setCheckNumberMini(1);
            }
        }
        dataPushCountDTO.setCheckNumber(1);
        //merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);

        // 进行撞库操作
        //判断是否为掩码撞库
        PushApiResult pushApiResult = null;
        //判断上游是否为掩码撞库渠道,如果是，只进行掩码撞库，如果不是，则全类型撞库
        if (StringUtils.equals(CheckStatusEnum.MOBILEMASK.getValue(), baseInfoByCode.getCheckType())){
            //掩码撞库
            pushApiResult = PushApi2Factory.getService(merchantBaseInfo.getFactoryType()).checkUserCode(orderNo, pushApiKeyParam, memberSourceInfo, extJson);
        }else {
            //全类型撞库
            pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType()).checkUser(orderNo, pushApiKeyParam, memberSourceInfo, extJson);
        }
        //PushApiResult pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType()).checkUser(orderNo, pushApiKeyParam, memberSourceInfo, extJson);
        log.info("【APIS商户信息匹配】uv 撞库结果【pushApiResult】{}【orderNo】{}【uid】{}", JSON.toJSONString(pushApiResult), orderNo, memberSourceInfo.getUid());
        MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
        updateEntity.setId(dataPushInfo.getId());
        updateEntity.setParamInfo(pushApiResult.getParamInfo());
        updateEntity.setCode(pushApiResult.getCode());
        updateEntity.setMessage(pushApiResult.getMessage());
        updateEntity.setResultInfo(pushApiResult.getResultInfo());
        updateEntity.setOutOrderNo(pushApiResult.getOutOrderNo());
        updateEntity.setApproveUrl(pushApiResult.getApproveUrl());
        updateEntity.setExtJson(JSON.toJSONString(extJson));



        // 判断是否为机构分润, 如果是，获取分润后价格存入
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(merchantBaseInfo.getPriceType())) {
            BigDecimal profitPrice = pushApiResult.getPriceRight();

            // 检查 CheckMinPrice 是否为空
            if (profitPrice != null && merchantBaseInfo.getCheckMinPrice() != null) {
                if (profitPrice.compareTo(merchantBaseInfo.getCheckMinPrice()) < 0) {
                    pushApiResult.setCode("300");
                    pushApiResult.setPushSuccess(false);
                    pushApiResult.setMessage("返回价格过低：" + profitPrice);

                    updateEntity.setCode(updateEntity.getCode()+"｜300");
                    updateEntity.setMessage(updateEntity.getMessage()+"|"+"返回价格过低："+profitPrice);
                }
            }
            updateEntity.setOriginAmount(pushApiResult.getPrice());
            updateEntity.setPriceAmount(profitPrice);
            merchantOrderDTO.setPriceAmount(profitPrice);
            matchMerchantInfo.setProfitAmount(profitPrice);//分润后价格账单
        }

        // 撞库失败，直接更新撞库失败结果
        if (!pushApiResult.isPushSuccess()){
            merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);
            // 推送失败  更新推送结果
            updateEntity.setStatus(PushStatusEnum.MATCH_FAILED.getValue());
            boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);
            log.info("【APIS商户信息匹配】撞库失败，更新订单结果【updateRes】{}【orderNo】{}【uid】{}",
                    updateRes, orderNo, memberSourceInfo.getUid());

            return matchMerchantInfo;
        }
        //如果是测试全流程撞库,非待推送状态 就不会推送
//        String uid = String.valueOf(memberSourceInfo.getUid());
//        if(StrUtil.equals(uid,"1871156854654963713")){
//            updateEntity.setStatus(PushStatusEnum.MATCH_FAILED.getValue());
//        }
            updateEntity.setStatus(PushStatusEnum.WAIT_PUSH.getValue());

        // 不需要授权，可以直接推送
        boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);
        log.info("【APIS商户信息匹配】API类型机构，撞库成功，更新订单结果【updateRes】{}【orderNo】{}【uid】{}",
                updateRes, orderNo, memberSourceInfo.getUid());
        matchMerchantInfo.setMatchSuccess(true);

        dataPushCountDTO.setCheckNumber(1);
        if (baseInfoByCode != null) {
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APP.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberApp(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.H5.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberH5(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIS.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberApis(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIB.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberApib(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.WX.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberMini(1);
            }
        }
        dataPushCountDTO.setCheckSuccessNumber(1);
        merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);

        return matchMerchantInfo;

    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public DataPushResult pushToMerchant(MerchantOrderDTO merchantOrderDTO, MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) throws Exception {

        MerchantDataPushInfo merchantDataPushInfo = merchantDataPushInfoMapper.getEntityByOrderNoLock(String.valueOf(merchantOrderDTO.getPushPoolId()));
        DataPushResult dataPushResult = new DataPushResult();
        if (PushStatusEnum.WAIT_PUSH.getValue().equals(merchantDataPushInfo.getStatus()) || PushStatusEnum.INIT.getValue().equals(merchantDataPushInfo.getStatus())) {
            JSONObject extJson = new JSONObject();
            if (StrUtil.isNotEmpty(merchantDataPushInfo.getExtJson())) {
                extJson = JSON.parseObject(merchantDataPushInfo.getExtJson());
            }

            // 注册统计
            DataPushCountDTO dataPushCountDTO = new DataPushCountDTO();
            dataPushCountDTO.setDateInfo(LocalDate.now().toString());
            dataPushCountDTO.setInfoId(merchantBaseInfo.getId());
            dataPushCountDTO.setInfoName(merchantBaseInfo.getInfoName());
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(memberSourceInfo.getChannelCode());
            if (baseInfoByCode != null) {
                if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APP.getValue())) {
                    dataPushCountDTO.setRegisterNumberApp(1);
                }
                if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.H5.getValue())) {
                    dataPushCountDTO.setRegisterNumberH5(1);
                }
                if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIS.getValue())) {
                    dataPushCountDTO.setRegisterNumberApis(1);
                }
                if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIB.getValue())) {
                    dataPushCountDTO.setRegisterNumberApib(1);
                }
                if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.WX.getValue())) {
                    dataPushCountDTO.setRegisterNumberMini(1);
                }
            }
            dataPushCountDTO.setRegisterNumber(1);


            extJson.put("orderId", String.valueOf(merchantOrderDTO.getOrderId()));
            extJson.put("orderItemId", String.valueOf(merchantOrderDTO.getOrderItemId()));

            PushApiKeyParam pushApiKeyParam = merchantDataPushInfoService.getPushKeyInfo(merchantBaseInfo, memberSourceInfo);
            String orderNo = String.valueOf(merchantDataPushInfo.getId());
            PushApiResult pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                    .registerUser(orderNo, merchantDataPushInfo.getOutOrderNo(), pushApiKeyParam, memberSourceInfo, extJson);
            log.info("【APIS商户信息匹配】推送结果【pushApiResult】{}【orderNo】{}【uid】{}", JSON.toJSONString(pushApiResult), orderNo, memberSourceInfo.getUid());

            if (ObjectUtil.hasEmpty(pushApiResult.getStatus(), pushApiResult.isPushSuccess(), pushApiResult.isSettleFlag())) {
                throw new RuntimeException("状态/推送状态/结算标志有空值");
            }

//            调用前端接口发送消息
            if(StrUtil.equals(pushApiResult.getStatus(), PushStatusEnum.FAILED.getValue())){
                try {
                    JSONObject data = new JSONObject();
                    data.put("InfoId", merchantBaseInfo.getId());
                    data.put("channelCode", memberSourceInfo.getChannelCode());
                    data.put("infoName", merchantBaseInfo.getInfoName());
                    data.put("uid", memberSourceInfo.getUid());
                    data.put("msg", pushApiResult.getMessage());
                    String url = "https://adminapi.hlai.hengtdb.com/merchant/pushInfo/getRegisterException";
                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_JSON);
                    HttpEntity<JSONObject> requestEntity = new HttpEntity<>(data, headers);
                    restTemplate.postForEntity(url, requestEntity, String.class);
                } catch (RestClientException e) {
                    log.info("发送失败通知异常, infoId={}, uid={}", merchantBaseInfo.getId(), memberSourceInfo.getUid());
                }
            }

            if (pushApiResult.isPushSuccess()) {
                // 注册成功统计
                dataPushCountDTO.setRegisterSuccessNumber(1);
                if (baseInfoByCode != null) {
                    if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APP.getValue())) {
                        dataPushCountDTO.setRegisterSuccessNumberApp(1);
                    }
                    if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.H5.getValue())) {
                        dataPushCountDTO.setRegisterSuccessNumberH5(1);
                    }
                    if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIS.getValue())) {
                        dataPushCountDTO.setRegisterSuccessNumberApis(1);
                    }
                    if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIB.getValue())) {
                        dataPushCountDTO.setRegisterSuccessNumberApib(1);
                    }
                    if (org.apache.commons.lang3.StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.WX.getValue())) {
                        dataPushCountDTO.setRegisterSuccessNumberMini(1);
                    }
                }
            }
            merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);

            MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
            updateEntity.setId(merchantDataPushInfo.getId());
            updateEntity.setUid(memberSourceInfo.getUid());
            updateEntity.setOrderId(merchantOrderDTO.getOrderId());
            updateEntity.setOrderItemId(merchantOrderDTO.getOrderItemId());
            updateEntity.setParamInfo(pushApiResult.getParamInfo());
            updateEntity.setResultInfo(pushApiResult.getResultInfo());
            updateEntity.setCode(pushApiResult.getCode());
            updateEntity.setMessage(pushApiResult.getMessage());
            updateEntity.setStatus(pushApiResult.getStatus());
            updateEntity.setOutOrderNo(pushApiResult.getOutOrderNo());

            boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);
            log.info("【APIS商户信息匹配】更新推送结果【updateRes】{}【orderNo】{}", updateRes, orderNo);

            if (ObjectUtil.isNotEmpty(memberSourceInfo) && pushApiResult.isPushSuccess()) {
                String phone = memberSourceInfo.getMobile();
                String realName = memberSourceInfo.getRealname();
                String companyName = merchantBaseInfo.getCompanyName();
                if (PhoneUtil.isMobile(phone) && org.apache.commons.lang3.StringUtils.isNotEmpty(realName) && org.apache.commons.lang3.StringUtils.isNotEmpty(companyName)) {
                    SmsParamDTO smsParamDTO = new SmsParamDTO();
                    smsParamDTO.setOtype("4");
                    smsParamDTO.setMobie(phone);

                    // 推送，短信提醒
                    JSONArray jsonArray = new JSONArray();
                    jsonArray.add(realName);
                    jsonArray.add(companyName);
                    smsParamDTO.setParamArray(jsonArray);

                    ChannelBaseInfo channelBaseInfo = channelCommonService.getBaseInfoByCode(memberSourceInfo.getChannelCode());
                    ApplicationInfo applicationInfo = applicationInfoService.getAppInfoByAppCode(channelBaseInfo.getAppCode());
                    ResponseVo responseVo = smsRecordService.sendSms(smsParamDTO, applicationInfo, channelBaseInfo);
                    log.info("【APIS】进件成功发送提醒短信【responseVo】{}", JSON.toJSONString(responseVo));
                }
            }
            dataPushResult.setPushSuccess(pushApiResult.isPushSuccess());
            dataPushResult.setSettleFlag(pushApiResult.isSettleFlag());
            dataPushResult.setPushOrderId(String.valueOf(merchantDataPushInfo.getId()));
        }else {
            dataPushResult.setPushSuccess(false);
            dataPushResult.setSettleFlag(false);
            dataPushResult.setPushOrderId(String.valueOf(merchantDataPushInfo.getId()));
        }
        return dataPushResult;
    }




    @Override
    public MatchMerchantInfo sourceCheckWithMerchant(MerchantBaseInfo merchantBaseInfo, MerchantOrderDTO merchantOrderDTO, CheckSourceTypeDTO checkSourceTypeDTO) throws Exception {

        MatchMerchantInfo matchMerchantInfo =  new MatchMerchantInfo();
        matchMerchantInfo.setMatchSuccess(false);

        matchMerchantInfo.setApproveFlag(0);

        /**
         * 生成匹配记录
         */
        MemberSourceInfo memberSourceInfo = checkSourceTypeDTO.getMemberSourceInfo();
        String checkType = checkSourceTypeDTO.getCheckType();
        PushApiKeyParam pushApiKeyParam = merchantDataPushInfoService.getPushKeyInfo(merchantBaseInfo, memberSourceInfo);
        // 设置授权协议地址
        matchMerchantInfo.setProtocolUrl(pushApiKeyParam.getProtocolUrl());
        JSONObject extJson = new JSONObject();

        MerchantDataPushInfo dataPushInfo = new MerchantDataPushInfo();

        dataPushInfo.setPriceAmount(merchantOrderDTO.getPriceAmount());
        dataPushInfo.setDateInfo(LocalDate.now().toString());
        dataPushInfo.setInfoId(merchantOrderDTO.getInfoId());
        dataPushInfo.setTaskId(merchantOrderDTO.getTaskId());
        dataPushInfo.setDeptId(merchantOrderDTO.getDeptId());

        dataPushInfo.setCostAmount(merchantOrderDTO.getCostAmount());
        dataPushInfo.setPayAmount(merchantOrderDTO.getPayAmount());
        dataPushInfo.setUid(memberSourceInfo.getUid());
        dataPushInfo.setChannelCode(memberSourceInfo.getChannelCode());
        dataPushInfo.setChannelName(memberSourceInfo.getChannelName());
        dataPushInfo.setAppCode(memberSourceInfo.getAppCode());
        dataPushInfo.setAppName(memberSourceInfo.getAppName());

        dataPushInfo.setStatus(PushStatusEnum.INIT.getValue());
        dataPushInfo.setApproveFlag(0);
        boolean save = merchantDataPushInfoService.save(dataPushInfo);

        // 资质撞库统计
        DataPushCountDTO dataPushCountDTO = new DataPushCountDTO();
        dataPushCountDTO.setDateInfo(LocalDate.now().toString());
        dataPushCountDTO.setInfoId(merchantBaseInfo.getId());
        dataPushCountDTO.setInfoName(merchantBaseInfo.getInfoName());
//        dataPushCountDTO.setCheckNumber(1);

//        merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);
        ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(memberSourceInfo.getChannelCode());
        if (baseInfoByCode != null) {
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APP.getValue())) {
                dataPushCountDTO.setCheckNumberApp(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.H5.getValue())) {
                dataPushCountDTO.setCheckNumberH5(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIS.getValue())) {
                dataPushCountDTO.setCheckNumberApis(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIB.getValue())) {
                dataPushCountDTO.setCheckNumberApib(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.WX.getValue())) {
                dataPushCountDTO.setCheckNumberMini(1);
            }
        }
        dataPushCountDTO.setCheckNumber(1);

        Long startTime = System.currentTimeMillis();
        // 进行撞库操作
        //判断是否为掩码撞库
        PushApiResult pushApiResult = null;
        if (ObjectUtil.equal(CheckStatusEnum.MOBILEMASK.getValue(), checkType)){
            //掩码撞库
            pushApiResult = PushApi2Factory.getService(merchantBaseInfo.getFactoryType()).checkUserCode(String.valueOf(dataPushInfo.getId()), pushApiKeyParam, memberSourceInfo, extJson);
        }else {
            //MD5撞库
            pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType()).checkUser(String.valueOf(dataPushInfo.getId()), pushApiKeyParam, memberSourceInfo, extJson);
        }
        //PushApiResult pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType()).checkUser(String.valueOf(dataPushInfo.getId()), pushApiKeyParam, memberSourceInfo, extJson);
        Long execTime = System.currentTimeMillis() - startTime;
        sourceLog.info("【APIS商户信息匹配】source 撞库结果【uid】{}【execTime】{}【pushApiResult】{}", memberSourceInfo.getUid(), execTime, JSON.toJSONString(pushApiResult));


        MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
        updateEntity.setId(dataPushInfo.getId());
        updateEntity.setParamInfo(pushApiResult.getParamInfo());
        updateEntity.setCheckExecTime(execTime);
        updateEntity.setCode(pushApiResult.getCode());
        updateEntity.setMessage(pushApiResult.getMessage());
        updateEntity.setResultInfo(pushApiResult.getResultInfo());
        updateEntity.setOutOrderNo(pushApiResult.getOutOrderNo());
        updateEntity.setApproveUrl(pushApiResult.getApproveUrl());
        updateEntity.setExtJson(JSON.toJSONString(extJson));


        // 判断是否为机构分润, 如果是，获取分润后价格存入
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(merchantBaseInfo.getPriceType())) {
            BigDecimal profitPrice = pushApiResult.getPriceRight();

            // 检查 profitPrice 和 CheckMinPrice 是否为空
            if (profitPrice != null && merchantBaseInfo.getCheckMinPrice() != null) {
                if (profitPrice.compareTo(merchantBaseInfo.getCheckMinPrice()) < 0) {
                    pushApiResult.setCode("300");
                    pushApiResult.setPushSuccess(false);
                    pushApiResult.setMessage("返回价格过低：" + profitPrice);

                    updateEntity.setCode(updateEntity.getCode()+"｜300");
                    updateEntity.setMessage(updateEntity.getMessage()+"|"+"返回价格过低："+profitPrice);
                }
            }

            updateEntity.setOriginAmount(pushApiResult.getPrice());
            updateEntity.setPriceAmount(profitPrice);
            merchantOrderDTO.setPriceAmount(profitPrice);
        }



        if (!pushApiResult.isPushSuccess()){
            //上游撞库失败统计
            merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);
            updateEntity.setStatus(PushStatusEnum.MATCH_FAILED.getValue());
        }else{
            matchMerchantInfo.setMatchSuccess(true);

            //撞库成功统计
             dataPushCountDTO.setCheckNumber(1);
        if (baseInfoByCode != null) {
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APP.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberApp(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.H5.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberH5(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIS.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberApis(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.APIB.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberApib(1);
            }
            if (StringUtils.equals(baseInfoByCode.getFlowRateType(), FlowRateTypeEnum.WX.getValue())) {
                dataPushCountDTO.setCheckSuccessNumberMini(1);
            }
        }
            dataPushCountDTO.setCheckSuccessNumber(1);
            merchantDataPushCountInfoService.updateDatePushCountInfo(dataPushCountDTO);
        }

        boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);

        String orderNo = String.valueOf(dataPushInfo.getId());
        matchMerchantInfo.setPushId(orderNo);
        matchMerchantInfo.setApproveUrl(pushApiResult.getApproveUrl());
        matchMerchantInfo.setMd5List(pushApiResult.getMd5List());

        return matchMerchantInfo;
    }

}
